package com.stray.demon.websocket.util;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.stray.demon.websocket.app.App;
import com.stray.demon.websocket.client.JWebSocketClient;
import com.stray.demon.websocket.core.Constant;

import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

/**
 * WebSocket 连接工具
 *
 * @author ydh
 * @date 2020/11/30 16:48
 */
public class JWebSocketUil {

    private JWebSocketClient client;
    private Comparable<String> comparable;

    private static JWebSocketUil instance = null;

    private JWebSocketUil() {
    }

    public static JWebSocketUil getInstance() {
        if (instance == null) {
            synchronized (JWebSocketUil.class) {
                if (instance == null) {
                    instance = new JWebSocketUil();
                }
            }
        }
        return instance;
    }

    /**
     * 通知回调
     *
     * @param comparable
     */
    public void setComparable(Comparable<String> comparable) {
        this.comparable = comparable;
    }

    /**
     * 初始化websocket连接
     */
    public void initSocketClient() {
        URI uri = URI.create(Constant.WS);
        client = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                Log.e("JWebSocketClientService", "收到的消息：" + message);
                Intent intent = new Intent();
                intent.setAction(Constant.WEB_SOCKET_CONTENT);
                intent.putExtra("message", message);
                App.getApp().sendBroadcast(intent);
                if (comparable != null) {
                    comparable.compareTo(message);
                }
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                Log.e("JWebSocketClientService", "websocket连接成功");
            }
        };
        connect();
    }

    /**
     * 连接websocket
     */
    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMsg(String msg) {
        if (null != client) {
            Log.e("JWebSocketClientService", "发送的消息：" + msg);
            client.send(msg);
        }
    }

    /**
     * @return WebSocket 是否连接
     */
    public Boolean isOpen() {
        return client != null && client.isOpen();
    }

    /**
     * 断开连接
     */
    public void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }


    //-------------------------------------websocket心跳检测------------------------------------------------
    //每隔10秒进行一次对长连接的心跳检测
    private static final long HEART_BEAT_RATE = 10 * 1000;

    /**
     * 开启心跳检测
     */
    public void handlerBeat() {
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
    }

    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }
            } else {
                //如果client已为空，重新初始化连接
                client = null;
                initSocketClient();
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.e("JWebSocketClientService", "开启重连");
                    client.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
